package com.yanti.service.impl;

import com.yanti.filter.LoginUserContextHolder;
import com.yanti.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;
import java.util.Set;

import static com.yanti.domain.enums.RedisKeyEnum.CHAT_HISTORY_KEY_PREFIX;

@RequiredArgsConstructor
//@Component
@Repository
public class RedisChatHistory implements ChatHistoryRepository {

    private final StringRedisTemplate redisTemplate;

//    private final static String CHAT_HISTORY_KEY_PREFIX = "chat:history:";

    @Override
    public void save(String type, String chatId) {
        String key = CHAT_HISTORY_KEY_PREFIX.getKey() + type
                + ":" + LoginUserContextHolder.getUserId();
        if(!Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, chatId))){
            redisTemplate.opsForSet().add(key, chatId);
        }
    }
    @Override
    public List<String> getChatIds(String type) {
        String key = CHAT_HISTORY_KEY_PREFIX.getKey() + type
                + ":" + LoginUserContextHolder.getUserId();
        Set<String> chatIds = redisTemplate.opsForSet().members(key);
        if(chatIds == null || chatIds.isEmpty()) {
            return Collections.emptyList();
        }
        return chatIds.stream().sorted(String::compareTo).toList();
    }
}